<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.word" clearable placeholder="名称" style="width: 160px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="类型" clearable class="filter-item" style="width: 120px" @change="handleFilter">
        <el-option key="1" label="前缀" :value="1" />
        <el-option key="2" label="词根" :value="2" />
        <el-option key="3" label="后缀" :value="3" />
      </el-select>
      <el-date-picker
        v-model="qdate"
        type="daterange"
        align="right"
        style="margin-bottom: 10px;vertical-align: middle;"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="downloadExcel">
        导出
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh-left" @click="reBuildRa">
        重新生成
      </el-button>
      <!-- <router-link :to="'/englishArtifact/word/uploadData'">
        <el-button class="filter-item" style="margin-left: 10px;" type="warning">
          导入
        </el-button>
      </router-link> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" sortable="custom" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type === 1 ? '': (row.type === 2 ? 'success': 'warning')">{{row.type === 1 ? '前缀': (row.type === 2 ? '词根': '后缀')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="单词数量" align="center">
        <template slot-scope="{row}">
          <router-link :to="{path: '/englishArtifact/word/word', query: {type: row.type, name: row.name}}">
            {{ row.count }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="释义" align="center">
        <template slot-scope="{row}">
          {{ row.ph }}
        </template>
      </el-table-column>
      <el-table-column label="时间" prop="add_time" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>录入：{{ row.addTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span><br>
          <span>更新：{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="showUpdateDialog(row)">
            修改
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-remove" @click="deleteMobile(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!--修改mobile-->
    <el-dialog :visible.sync="updateDialog" :title="isAdd ? '新增单词' : '编辑单词'" append-to-body width="720px">
      <el-form ref="form" :model="form" :rules="rules" :inline="false" size="small" label-width="80px">
        <el-form-item label="名称：" prop="name">
          <template>
            <el-input v-model="form.name" placeholder="名称" />
          </template>
        </el-form-item>
        <el-form-item label="名称：" prop="type">
          <template>
            <el-select v-model="form.type" placeholder="类型" clearable>
              <el-option key="1" label="前缀" :value="1" />
              <el-option key="2" label="词根" :value="2" />
              <el-option key="3" label="后缀" :value="3" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="释义" prop="logisticsNo">
          <template>
            <el-input v-model="form.ph" type="textarea" :autosize="{ minRows: 3, maxRows: 6}" placeholder="释义" />
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import edit from './module/edit'
import { getList, save, update, deleteMobile, downloadExcel, reBuildRa } from '@/api/word/ra'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'QaUser',
  components: { Pagination },
  filters: {
  },
  data() {
    return {
      detailDialog: false,
      updateDialog: false,
      wpDialog: false,
      isAdd: true,
      form: {
        changeIntegral: 0,
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }]
      },
      defaultRa: {'id': Math.floor(Math.random()*100000000), name: '', ph: ''},
      loading: false,
      syncLoading: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        page: 1,
        size: 10,
        sort: 'update_time',
        order: 'desc'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      supThis: this,
      qdate: [],
      currentUser: {},
      goods: [
        { 'label': '政治押题库', 'value': '525033992', 'children': [{ 'label': '选择题', 'value': '1' }, { 'label': '分析题', 'value': '2' }, { 'label': '选择题+分析题', 'value': '3' }] }
      ],
      wpList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.qdate && this.qdate.length === 2) {
        this.listQuery.startTime = this.qdate[0]
        this.listQuery.endTime = this.qdate[1]
      } else {
        this.listQuery.startTime = this.listQuery.endTime = null
      }
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      }).catch(err => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.size = 10
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sort = prop
      if(order === 'ascending'){
        this.listQuery.order = 'asc'
      }else {
        this.listQuery.order = 'desc'
      }
      this.handleFilter()
    },
    showUpdateDialog(row) {
      this.form = Object.assign({}, row)
      this.updateDialog = true
      this.isAdd = false
    },
    addItem(row, idx){
      row.raList.splice(idx+1, 0, Object.assign({}, this.defaultRa))
    },
    removeItem(row, idx) {
      row.raList.splice(idx, 1)
    },
    handleCreate(row) {
      this.resetForm()
      this.updateDialog = true
      this.isAdd = true
    },
    deleteMobile(row) {
      this.$confirm('确定删除该词根词缀?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMobile(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        })
      }).catch(() => {})
    },
    reBuildRa() {
      this.$confirm('确定重新生成所有的词根词缀? 生成时间较长，请耐心等待!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        reBuildRa().then(res => {
          this.$message({
            type: 'success',
            message: '生成成功!'
          })
          this.getList()
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '生成失败，请联系管理员!'
          })
          this.listLoading = false
        })
      }).catch(() => {})
    },
    // 隐藏弹框
    cancel() {
      this.updateDialog = false
      this.wpDialog = false
    },
    // 修改
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.id) {
            update(this.form).then(res => {
              this.resetForm()
              this.$notify({
                title: '修改成功',
                type: 'success',
                duration: 2500
              })
              this.loading = false
              this.updateDialog = false
              this.getList()
            }).catch(err => {
              this.loading = false
              console.log(err)
            })
          } else {
            save(this.form).then(res => {
              this.resetForm()
              this.$notify({
                title: '新增成功',
                type: 'success',
                duration: 2500
              })
              this.loading = false
              this.updateDialog = false
              this.getList()
            }).catch(err => {
              this.loading = false
              this.$message({
                type: 'error',
                message: err || '删除失败!'
              })
              console.log(err)
            })
          }
        }
      })
    },
    downloadExcel() {
      this.listLoading = true
      downloadExcel(this.listQuery).then(response => {
        this.download(response)
        this.listLoading = false
      }).catch((e) => {
        console.log(e)
        this.listLoading = false
      })
    },
    download(data) {
      if (!data || !data.data) {
        return
      }
      var blob = new Blob([data.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      var url = window.URL.createObjectURL(blob)
      var aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.href = url
      var fileName = '词根词缀-' + new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '.xlsx'
      aLink.setAttribute('download', fileName)
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink)
      window.URL.revokeObjectURL(url)
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    resetForm() {
      this.form = { 'name': undefined, raList: [Object.assign({}, this.defaultRa)] }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style>
.question_topic_tree_search{
  width: 200px;
  display: inline-block;
  margin-bottom: 10px;
  vertical-align: middle;
  line-height:35px
}
.row{
  margin-bottom: 20px;
}
</style>

